package com.wl.shop.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wl.shop.dao.MenuDao;
import com.wl.shop.entity.Menu;
import com.wl.shop.utils.CacheUtils;
import com.wl.shop.utils.LogUtils;
import com.wl.shop.utils.UserUtils;

@Service("menuService")
@Transactional(readOnly = true)
public class MenuService{
	@Autowired
	private MenuDao menuDao;
	
	public Page<Menu> listByParam(Page<Menu> page,EntityWrapper<Menu> wrapper){
		if(page.getSize()<=0){
			page.setSize(getCount(wrapper));
		}
		List<Menu> menuList =menuDao.selectPage(page, wrapper);
		page.setRecords(menuList);
		return page;
	}
	
	public int getCount(EntityWrapper<Menu> wrapper){
		return menuDao.selectCount(wrapper);
	}
	
	public int updateAll(Menu menu,EntityWrapper<Menu> wrapper){
		menu.preUpdate();
		int p = menuDao.update(menu, wrapper);
		// 清除用户菜单缓存
		UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
		// 清除用户菜单树缓存
		UserUtils.removeCache(UserUtils.CACHE_TREE_MENU_STRING);
		// 清除日志相关缓存
		CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
		return p;
	}
	
	public void saveOrUpdate(Menu menu){
		if(menu.getId() == null || "".equals(menu.getId())){
			menu.preInsert();
			menuDao.insert(menu);
		}else{
			menu.preUpdate();
			menuDao.updateById(menu);
		}
		// 清除用户菜单缓存
		UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
		// 清除用户菜单树缓存
		UserUtils.removeCache(UserUtils.CACHE_TREE_MENU_STRING);
		// 清除日志相关缓存
		CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
	}
	
	public List<Menu> listByParam(EntityWrapper<Menu> wrapper){
		return menuDao.selectList(wrapper);
	}
	
	public int getMaxSort(String parentId){
		Integer s = menuDao.selectMaxSort(parentId);
		return s==null?0:s.intValue();
	}
	
	public Menu selectById(String id){
		return menuDao.selectById(id);
	}
	
}
